<template>
  <a-row justify="center">
    <a-col :span="16">
      <a-form :model="form" label-align="left">
        <a-form-item field="title" label="题目标题：">
          <a-input v-model="form.title" placeholder="请输入标题" />
        </a-form-item>
        <a-form-item field="tags" label="题目标签：">
          <a-input-tag
            v-model="form.tags"
            :style="{ width: '320px' }"
            placeholder="请输入标签"
            allow-clear
          />
        </a-form-item>
        <a-form-item field="content" label="题目内容：">
          <MDEditor :value="form.content" :handle-change="onContentChange" />
        </a-form-item>
        <a-form-item field="answer" label="题目答案：">
          <MDEditor :value="form.answer" :handle-change="onAnswerChange" />
        </a-form-item>
        <a-form-item
          label="题目配置："
          :content-flex="false"
          :merge-props="false"
          style="min-width: 480px"
        >
          <a-space direction="vertical">
            <a-form-item field="judgeConfig.timeLimit" label="时间限制">
              <a-input-number
                v-model="form.judgeConfig.timeLimit"
                placeholder="请输入限制时间"
                size="large"
                mode="button"
                min="0"
              />
            </a-form-item>
            <a-form-item field="judgeConfig.stackLimit" label="堆栈限制">
              <a-input-number
                v-model="form.judgeConfig.stackLimit"
                placeholder="请输入堆栈限制"
                size="large"
                mode="button"
                min="0"
              />
            </a-form-item>
            <a-form-item field="judgeConfig.memoryLimit" label="内存限制">
              <a-input-number
                v-model="form.judgeConfig.memoryLimit"
                placeholder="请输入内存限制"
                size="large"
                mode="button"
                min="0"
              />
            </a-form-item>
          </a-space>
        </a-form-item>
        <a-form-item
          label="判题配置："
          :content-flex="false"
          :merge-props="false"
          style="min-width: 480px"
        >
          <a-form-item
            v-for="(judgeCaseItem, index) of form.judgeCase"
            :key="index"
            no-style
          >
            <a-space direction="vertical" style="min-width: 480px">
              <a-form-item
                :field="`form.judgeCase[${index}].input`"
                :label="`输入用例 ${index + 1}：`"
                :key="index"
              >
                <a-input
                  v-model="judgeCaseItem.input"
                  placeholder="请输入测试输入用例"
                />
              </a-form-item>
              <a-form-item
                :field="`form.judgeCase[${index}].output`"
                :label="`输出用例 ${index + 1}：`"
                :key="index"
              >
                <a-input
                  v-model="judgeCaseItem.output"
                  placeholder="请输入测试输出用例"
                />
              </a-form-item>
              <a-button status="danger" @click="handleDelete(index)"
                >删除
              </a-button>
            </a-space>
          </a-form-item>

          <div style="margin-top: 16px">
            <a-button type="outline" @click="handleAdd()"
              >新增测试用例
            </a-button>
          </div>
        </a-form-item>

        <a-form-item>
          <a-button
            type="primary"
            style="margin-top: 16px; min-width: 100px"
            @click="onSubmitQuestionForm()"
            >提交
          </a-button>
        </a-form-item>
      </a-form>
    </a-col>
  </a-row>
</template>

<script setup lang="ts">
import { getCurrentInstance, onMounted, ref } from "vue";
import MDEditor from "@/components/MDEditor.vue";
import { QuestionControllerService } from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import { useRoute, useRouter } from "vue-router";

let form = ref({
  answer: "",
  content: "",
  judgeCase: [],
  judgeConfig: {
    memoryLimit: 0,
    stackLimit: 0,
    timeLimit: 0,
  },
  tags: [],
  title: "",
  userId: 0,
});

const route = useRoute();
const router = useRouter();
// 如果页面地址包含 update，视为更新页面
const updatePage = route.path.includes("update");

/**
 * 根据题目 id 获取原来数据
 */
const loadData = async () => {
  const id = route.query.id;
  if (!id) {
    return;
  }
  const res = await QuestionControllerService.getQuestionByIdUsingGet(
    id as any
  );
  if (res.code === 0) {
    form.value = res.data as any;
    // json 转 js 对象
    if (!form.value.judgeCase) {
      form.value.judgeCase = [
        {
          input: "",
          output: "",
        },
      ];
    } else {
      form.value.judgeCase = JSON.parse(form.value.judgeCase as any);
    }
    if (!form.value.judgeConfig) {
      form.value.judgeConfig = {
        memoryLimit: 1000,
        stackLimit: 1000,
        timeLimit: 1000,
      };
    } else {
      form.value.judgeConfig = JSON.parse(form.value.judgeConfig as any);
    }
    if (!form.value.tags) {
      form.value.tags = [];
    } else {
      form.value.tags = JSON.parse(form.value.tags as any);
    }
  } else {
    message.error("加载失败，" + res.message);
  }
};

/**
 * 页面加载时，请求数据
 */
onMounted(() => {
  loadData();
});

/**
 * 创建题目
 */
const onSubmitQuestionForm = async () => {
  // 区分是创建页面还是更新页面
  if (updatePage) {
    const res = await QuestionControllerService.updateQuestionUsingPost(
      form.value
    );
    if (res.code === 0) {
      message.success("更新成功");
      // 跳转到管理题目页面
      await router.push("/manage/question");
    } else {
      message.error("更新失败，" + res.message);
    }
    clearForm();
  } else {
    const res = await QuestionControllerService.addQuestionUsingPost(
      form.value
    );
    if (res.code === 0) {
      message.success("创建题目成功");
    } else {
      message.error("创建题目失败，" + res.message);
    }
    clearForm();
  }
};

/**
 * 新增判题用例
 */
const handleAdd = () => {
  form.value.judgeCase.push({
    input: "",
    output: "",
  });
};

// 清空表单对象
const clearForm = () => {
  form.value.answer = "";
  form.value.content = "";
  form.value.judgeCase = [];
  form.value.judgeConfig.memoryLimit = 0;
  form.value.judgeConfig.stackLimit = 0;
  form.value.judgeConfig.timeLimit = 0;
  form.value.tags = [];
  form.value.title = "";
  form.value.userId = 0;
  form.value.judgeCase = [];
};

/**
 * 删除判题用例
 * @param index
 */
const handleDelete = (index: number) => {
  form.value.judgeCase.splice(index, 1);
};

const onContentChange = (v: string) => {
  form.value.content = v;
};

const onAnswerChange = (v: string) => {
  form.value.answer = v;
};
</script>

<style scoped>
#addQuestionView {
}
</style>
